#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
批量处理器 - 核心批量处理逻辑
负责多季度数据的批量提取和汇总
"""

import os
import glob
import pandas as pd
from pathlib import Path
from collections import defaultdict
from datetime import datetime
import openpyxl
from openpyxl.styles import PatternFill, Font, Alignment
import logging

from core.extractor import DocumentExtractor
from core.data_processor import normalize_dose_value, check_dose_level
from utils.helpers import parse_quarters, ensure_directory, format_time_range
from app.config import APP_SETTINGS, CSV_FIELDNAMES


class BatchProcessor:
    """批量处理器类"""
    
    def __init__(self, excel_file_path=None, progress_callback=None):
        """初始化批量处理器
        
        Args:
            excel_file_path: Excel查询文件路径
            progress_callback: 进度回调函数，接受 (progress, text) 参数
        """
        self.excel_file_path = excel_file_path
        self.quarterly_data = defaultdict(dict)  # {季度: {样品编号: 完整数据记录}}
        self.all_sample_base_info = {}  # {样品编号: 基础信息}
        self.progress_callback = progress_callback
        
        # 设置详细日志
        self.logger = logging.getLogger('BatchProcessor')
        self.logger.setLevel(logging.DEBUG)
        
        # 文档处理跟踪
        self.processed_docs = set()
        self.skipped_docs = []
        self.error_docs = []
    
    def update_progress(self, progress, text=""):
        """更新进度
        
        Args:
            progress: 进度值 (0-100)
            text: 进度文本
        """
        if self.progress_callback:
            self.progress_callback(progress, text)
        
    def find_word_documents(self, base_dir, quarters):
        """在指定目录下查找所有季度的Word文档
        
        Args:
            base_dir: 数据根目录
            quarters: 季度列表
            
        Returns:
            dict: {季度: [文档路径列表]}
        """
        documents = defaultdict(list)
        base_path = Path(base_dir)
        
        # 追踪的任务编号列表
        tracked_tasks = ['JL252001', 'JL252701', 'JL252002', 'JL252336', 'JL252645', 'JL252166', 'JL252833', 'JL252748']
        
        self.logger.info(f"开始查找文档，数据目录: {base_dir}, 季度: {quarters}")
        
        for quarter in quarters:
            quarter_dir = base_path / quarter
            self.logger.info(f"正在处理季度: {quarter}, 目录: {quarter_dir}")
            
            if quarter_dir.exists():
                # 只查找个人剂量监测报告文档，跳过封面文档
                pattern = str(quarter_dir / "*" / "*.docx")
                all_word_files = glob.glob(pattern)
                self.logger.info(f"找到所有docx文件: {len(all_word_files)}个")
                
                # 过滤：只保留个人剂量监测报告文档，排除封面文档和临时文件
                word_files = []
                for f in all_word_files:
                    filename = os.path.basename(f)
                    task_id = Path(f).parent.name.split()[0]
                    
                    if (not filename.startswith('~$') and 
                        not filename.startswith('1.') and 
                        '封面' not in filename and
                        ('个人剂量监测报告' in filename or '2.' in filename)):
                        word_files.append(f)
                        
                        # 特别跟踪目标任务
                        if task_id in tracked_tasks:
                            self.logger.warning(f"★ 目标任务 {task_id} 文档被发现: {f}")
                    else:
                        # 记录被过滤的文件
                        if task_id in tracked_tasks:
                            self.logger.warning(f"★ 目标任务 {task_id} 文档被过滤: {f} (原因: {filename})")
                
                documents[quarter].extend(word_files)
                self.logger.info(f"找到 {quarter} 的个人剂量监测报告文档: {len(word_files)} 个")
                print(f"找到 {quarter} 的个人剂量监测报告文档: {len(word_files)} 个")
            else:
                self.logger.error(f"目录 {quarter_dir} 不存在")
                print(f"警告: 目录 {quarter_dir} 不存在")
        
        # 统计找到的目标任务
        total_found = sum(len(docs) for docs in documents.values())
        tracked_found = 0
        for quarter_docs in documents.values():
            for doc in quarter_docs:
                task_id = Path(doc).parent.name.split()[0]
                if task_id in tracked_tasks:
                    tracked_found += 1
        
        self.logger.info(f"文档发现统计: 总共{total_found}个, 目标任务{tracked_found}个")
        
        return documents
        
    def extract_quarter_data(self, quarter, document_paths, base_progress=0, progress_range=50):
        """提取某个季度的所有文档数据
        
        Args:
            quarter: 季度名称
            document_paths: 文档路径列表
            base_progress: 基础进度值
            progress_range: 这个季度占用的进度范围
            
        Returns:
            dict: {样品编号: 完整数据记录}
        """
        quarter_results = {}
        extractor = DocumentExtractor(self.excel_file_path)
        total_docs = len(document_paths)
        
        # 追踪的任务编号列表
        tracked_tasks = ['JL252001', 'JL252701', 'JL252002', 'JL252336', 'JL252645', 'JL252166', 'JL252833', 'JL252748']
        
        self.logger.info(f"开始提取{quarter}数据，共{total_docs}个文档")
        
        # 统计目标任务数量
        tracked_in_quarter = 0
        for doc_path in document_paths:
            task_id = Path(doc_path).parent.name.split()[0]
            if task_id in tracked_tasks:
                tracked_in_quarter += 1
                self.logger.warning(f"★ 目标任务 {task_id} 在待处理列表中: {doc_path}")
        
        self.logger.info(f"待处理列表中包含 {tracked_in_quarter} 个目标任务")
        
        for i, doc_path in enumerate(document_paths):
            # 获取任务编号（在try外面定义，避免在finally中未定义问题）
            task_id = Path(doc_path).parent.name.split()[0]
            is_tracked = task_id in tracked_tasks
            
            try:
                # 更新进度
                doc_progress = base_progress + (i / total_docs) * progress_range
                self.update_progress(doc_progress, f"处理{quarter}文档 {i+1}/{total_docs}")
                
                if is_tracked:
                    self.logger.warning(f"★ 开始处理目标任务 {task_id}: {doc_path}")
                else:
                    self.logger.debug(f"处理文档: {doc_path}")
                
                print(f"正在处理: {doc_path}")
                
                # 提取数据（现在返回人员列表）
                personnel_list = extractor.extract_from_file(doc_path)
                
                if is_tracked:
                    self.logger.warning(f"★ 目标任务 {task_id} 提取结果: {len(personnel_list) if personnel_list else 0}个人员")
                
                if not personnel_list:
                    if is_tracked:
                        self.logger.error(f"★ 目标任务 {task_id} 没有提取到人员信息: {doc_path}")
                        self.skipped_docs.append((task_id, doc_path, "无人员信息"))
                    else:
                        self.logger.debug(f"文档无人员信息: {doc_path}")
                    
                    print(f"警告: 文档 {doc_path} 没有提取到人员信息，跳过")
                    continue
                
                # 为每个人员创建记录
                for data in personnel_list:
                    sample_id = data.get('样品编号')
                    if not sample_id:
                        person_name = data.get('姓名', 'Unknown')
                        if is_tracked:
                            self.logger.error(f"★ 目标任务 {task_id} 人员缺少样品编号: {person_name}")
                        else:
                            self.logger.debug(f"人员缺少样品编号: {person_name}")
                        
                        print(f"警告: 人员记录没有样品编号，跳过: {person_name}")
                        continue
                        
                    # 标准化剂量值
                    dose_value = normalize_dose_value(data.get('剂量当量', 0))
                    
                    # 构建完整记录
                    complete_record = {
                        '受检单位名称': data.get('受检单位名称', ''),
                        '单位地址': data.get('单位地址', ''),
                        '省': data.get('省', ''),
                        '市': data.get('市', ''),
                        '区（镇）': data.get('区（镇）', ''),
                        '邮政编码': data.get('邮政编码', ''),
                        '收样日期': data.get('收样日期', ''),
                        '报告编号': data.get('报告编号', ''),
                        '检测日期': data.get('检测日期', ''),
                        '样品数量': data.get('样品数量', ''),
                        '检测仪器': data.get('检测仪器', ''),
                        '检测任务编号': data.get('检测任务编号', ''),
                        '部门': data.get('部门', ''),
                        '样品编号': sample_id,
                        '姓名': data.get('姓名', ''),
                        '身份证号': data.get('身份证号', ''),
                        '性别': data.get('性别', ''),
                        '射线及防护类型（是否穿铅衣）': data.get('射线及防护类型（是否穿铅衣）', ''),
                        '职业类别': data.get('职业类别', ''),
                        '佩戴周期': data.get('佩戴周期', ''),
                        '剂量当量': dose_value,
                        '是否超调查水平（1.25mSv）': '是' if dose_value >= APP_SETTINGS['QUARTERLY_DOSE_THRESHOLD'] else '否'
                    }
                    
                    # 保存到季度结果（使用检测任务编号+样品编号作为唯一键，避免覆盖）
                    unique_key = f"{task_id}_{sample_id}"
                    quarter_results[unique_key] = complete_record
                    
                    if is_tracked:
                        self.logger.warning(f"★ 目标任务 {task_id} 成功保存人员: {data.get('姓名')} (样品编号: {sample_id})")
                    
                    # 保存基础信息到全局（用于年度汇总表）
                    if unique_key not in self.all_sample_base_info:
                        self.all_sample_base_info[unique_key] = {
                            '受检单位名称': data.get('受检单位名称', ''),
                            '单位地址': data.get('单位地址', ''),
                            '省': data.get('省', ''),
                            '市': data.get('市', ''),
                            '区（镇）': data.get('区（镇）', ''),
                            '样品编号': sample_id,
                            '姓名': data.get('姓名', ''),
                            '性别': data.get('性别', ''),
                            '职业类别': data.get('职业类别', ''),
                        }
                
            except Exception as e:
                if is_tracked:
                    self.logger.error(f"★ 目标任务 {task_id} 处理失败: {str(e)}")
                    self.error_docs.append((task_id, doc_path, str(e)))
                else:
                    self.logger.error(f"文档处理失败: {doc_path}, 错误: {str(e)}")
                
                print(f"处理文档 {doc_path} 时出错: {e}")
            finally:
                # 记录已处理
                self.processed_docs.add(task_id)
                
        # 统计结果
        total_records = len(quarter_results)
        tracked_processed = sum(1 for task_id in tracked_tasks if task_id in self.processed_docs)
        
        self.logger.info(f"{quarter}季度处理完成: 总记录{total_records}个, 目标任务处理{tracked_processed}个")
        
        # 检查未处理的目标任务
        unprocessed_tracked = [task for task in tracked_tasks if task not in self.processed_docs]
        if unprocessed_tracked:
            self.logger.error(f"未处理的目标任务: {unprocessed_tracked}")
        
        return quarter_results
        
    def process_all_quarters(self, base_dir, time_range):
        """处理所有季度的数据
        
        Args:
            base_dir: 数据根目录
            time_range: 时间范围字符串
            
        Returns:
            list: 处理的季度列表
        """
        quarters = parse_quarters(time_range)
        print(f"处理季度: {quarters}")
        
        self.update_progress(5, "查找文档...")
        
        # 查找所有文档
        documents = self.find_word_documents(base_dir, quarters)
        
        self.update_progress(10, "开始提取数据...")
        
        # 提取每个季度的数据
        total_quarters = len(quarters)
        extraction_progress_range = 70  # 提取阶段占70%的进度
        
        for i, quarter in enumerate(quarters):
            if quarter in documents:
                print(f"\n=== 处理 {quarter} 季度 ===")
                
                # 计算当前季度的进度范围
                base_progress = 10 + (i / total_quarters) * extraction_progress_range
                quarter_progress_range = extraction_progress_range / total_quarters
                
                quarter_results = self.extract_quarter_data(
                    quarter, documents[quarter], 
                    base_progress, quarter_progress_range
                )
                
                # 保存到主数据结构
                self.quarterly_data[quarter] = quarter_results
        
        self.update_progress(80, "数据提取完成")
        return quarters
        
    def generate_quarterly_summary_csv(self, quarter, output_dir):
        """生成单个季度的汇总CSV文件
        
        Args:
            quarter: 季度名称，如 "2025Q1"
            output_dir: 输出目录
            
        Returns:
            str: 生成的CSV文件路径
        """
        if quarter not in self.quarterly_data or not self.quarterly_data[quarter]:
            print(f"季度 {quarter} 没有数据")
            return None
            
        # 准备数据行
        rows = []
        
        for i, (sample_id, record) in enumerate(sorted(self.quarterly_data[quarter].items()), 1):
            row = {'序号': i}
            row.update(record)
            rows.append(row)
            
        # 创建DataFrame
        df = pd.DataFrame(rows)
        
        # 定义季度汇总表的列顺序（使用配置文件中的字段顺序）
        quarterly_columns = ['序号'] + CSV_FIELDNAMES
        
        # 确保所有列都存在
        for col in quarterly_columns:
            if col not in df.columns:
                df[col] = ''
                
        # 重新排序列
        df = df[quarterly_columns]
        
        # 生成文件路径
        filename = f"{quarter}季度汇总表.csv"
        output_path = os.path.join(output_dir, filename)
        
        # 确保输出目录存在
        os.makedirs(output_dir, exist_ok=True)
        
        # 保存CSV
        df.to_csv(output_path, index=False, encoding='utf-8-sig')
        print(f"季度汇总表已保存到: {output_path}")
        print(f"共处理了 {len(rows)} 个样品")
        
        # 显示统计信息
        over_limit = len([r for r in rows if r['是否超调查水平（1.25mSv）'] == '是'])
        print(f"超调查水平的样品: {over_limit} 个")
        
        # 备份季度汇总表到历史目录
        self.backup_quarterly_summary(quarter, df)
        
        return output_path
        
    def generate_annual_summary_csv(self, quarters, output_dir):
        """从季度汇总数据生成年度汇总CSV文件
        
        Args:
            quarters: 季度列表
            output_dir: 输出目录
            
        Returns:
            str: 生成的CSV文件路径
        """
        if not self.quarterly_data:
            print("没有找到任何季度数据")
            return None
            
        # 准备数据行
        rows = []
        
        # 收集所有样品编号
        all_sample_ids = set()
        for quarter in quarters:
            if quarter in self.quarterly_data:
                all_sample_ids.update(self.quarterly_data[quarter].keys())
        
        for i, unique_key in enumerate(sorted(all_sample_ids), 1):
            # 获取基础信息
            base_info = self.all_sample_base_info.get(unique_key, {})
            
            # 从unique_key中提取纯样品编号
            if '_' in unique_key:
                pure_sample_id = unique_key.split('_', 1)[1]  # 提取_后面的部分
            else:
                pure_sample_id = unique_key
            
            row = {
                '序号': i,
                '单位名称': base_info.get('受检单位名称', ''),
                '单位地址': base_info.get('单位地址', ''),
                '省': base_info.get('省', ''),
                '市': base_info.get('市', ''),
                '区': base_info.get('区（镇）', ''),
                '样品编号': pure_sample_id,
                '姓名': base_info.get('姓名', ''),
                '性别': base_info.get('性别', ''),
                '职业类别': base_info.get('职业类别', ''),
            }
            
            # 添加每个季度的剂量当量
            total_dose = 0
            for quarter in quarters:
                dose = 0
                if quarter in self.quarterly_data and unique_key in self.quarterly_data[quarter]:
                    dose = self.quarterly_data[quarter][unique_key].get('剂量当量', 0)
                row[quarter] = dose
                total_dose += dose
                
            # 添加年有效剂量当量
            row['年有效剂量当量'] = total_dose
            
            # 判断是否超调查水平（年度阈值：大于等于5mSv）
            row['是否超调查水平（5mSv）'] = '是' if total_dose >= APP_SETTINGS['ANNUAL_DOSE_THRESHOLD'] else '否'
            
            rows.append(row)
            
        # 创建DataFrame
        df = pd.DataFrame(rows)
        
        # 定义年度汇总表的列顺序
        annual_columns = [
            '序号', '单位名称', '单位地址', '省', '市', '区', 
            '样品编号', '姓名', '性别', '职业类别'
        ] + quarters + ['年有效剂量当量', '是否超调查水平（5mSv）']
        
        # 确保所有列都存在
        for col in annual_columns:
            if col not in df.columns:
                df[col] = ''
                
        # 重新排序列
        df = df[annual_columns]
        
        # 生成文件路径
        filename = "年度汇总表.csv"
        output_path = os.path.join(output_dir, filename)
        
        # 确保输出目录存在
        os.makedirs(output_dir, exist_ok=True)
        
        # 保存CSV
        df.to_csv(output_path, index=False, encoding='utf-8-sig')
        print(f"年度汇总表已保存到: {output_path}")
        print(f"共处理了 {len(rows)} 个样品")
        
        # 显示统计信息
        over_limit = len([r for r in rows if r.get('是否超调查水平（5mSv）', r.get('是否超调查水平', '')) == '是'])
        print(f"超调查水平的样品: {over_limit} 个")
        
        return output_path
    
    def backup_quarterly_summary(self, quarter, df):
        """备份季度汇总表到历史目录
        
        Args:
            quarter: 季度名称
            df: 数据框
        """
        try:
            # 创建历史备份目录
            archives_dir = os.path.join(os.getcwd(), APP_SETTINGS['QUARTERLY_ARCHIVES_DIR'])
            ensure_directory(archives_dir)
            
            # 保存最新的季度汇总表（覆盖旧的）
            archive_filename = f"{quarter}季度汇总表.csv"
            archive_path = os.path.join(archives_dir, archive_filename)
            
            df.to_csv(archive_path, index=False, encoding='utf-8-sig')
            print(f"季度汇总表已备份到: {archive_path}")
            
        except Exception as e:
            print(f"备份季度汇总表时出错: {e}")
    
    def load_historical_quarterly_data(self, quarters):
        """从历史备份中加载季度数据
        
        Args:
            quarters: 季度列表
            
        Returns:
            dict: {季度: DataFrame} 或 None如果有缺失的季度
        """
        historical_data = {}
        missing_quarters = []
        
        archives_dir = os.path.join(os.getcwd(), APP_SETTINGS['QUARTERLY_ARCHIVES_DIR'])
        
        for quarter in quarters:
            archive_filename = f"{quarter}季度汇总表.csv"
            archive_path = os.path.join(archives_dir, archive_filename)
            
            if os.path.exists(archive_path):
                try:
                    df = pd.read_csv(archive_path, encoding='utf-8-sig')
                    historical_data[quarter] = df
                    print(f"加载历史数据: {archive_path}")
                except Exception as e:
                    print(f"加载 {archive_path} 时出错: {e}")
                    missing_quarters.append(quarter)
            else:
                missing_quarters.append(quarter)
        
        if missing_quarters:
            print(f"缺少历史季度数据: {', '.join(missing_quarters)}")
            return None
            
        return historical_data
    
    def generate_annual_from_historical(self, quarters, output_dir):
        """从历史季度数据生成年度汇总表
        
        Args:
            quarters: 季度列表
            output_dir: 输出目录
            
        Returns:
            str: 生成的CSV文件路径，失败返回None
        """
        # 加载历史数据
        historical_data = self.load_historical_quarterly_data(quarters)
        if historical_data is None:
            return None
        
        self.update_progress(90, "从历史数据生成年度汇总表...")
        
        # 收集所有样品信息
        all_samples = {}
        
        for quarter, df in historical_data.items():
            for _, row in df.iterrows():
                sample_id = row.get('样品编号', '')
                if not sample_id:
                    continue
                
                if sample_id not in all_samples:
                    all_samples[sample_id] = {
                        '单位名称': row.get('受检单位名称', ''),
                        '单位地址': row.get('单位地址', ''),
                        '省': row.get('省', ''),
                        '市': row.get('市', ''),
                        '区': row.get('区（镇）', ''),
                        '样品编号': sample_id,
                        '姓名': row.get('姓名', ''),
                        '性别': row.get('性别', ''),
                        '职业类别': row.get('职业类别', ''),
                    }
                    # 初始化所有季度为0
                    for q in quarters:
                        all_samples[sample_id][q] = 0
                
                # 设置当前季度的剂量
                dose = row.get('剂量当量', 0)
                try:
                    all_samples[sample_id][quarter] = float(dose) if dose else 0
                except (ValueError, TypeError):
                    all_samples[sample_id][quarter] = 0
        
        # 生成年度汇总表
        rows = []
        for i, (sample_id, sample_data) in enumerate(sorted(all_samples.items()), 1):
            row = {'序号': i}
            row.update(sample_data)
            
            # 计算年有效剂量当量
            total_dose = sum(sample_data.get(q, 0) for q in quarters)
            row['年有效剂量当量'] = total_dose
            
            # 判断是否超调查水平（年度阈值：大于等于5mSv）
            row['是否超调查水平（5mSv）'] = '是' if total_dose >= APP_SETTINGS['ANNUAL_DOSE_THRESHOLD'] else '否'
            
            rows.append(row)
        
        # 创建DataFrame
        df = pd.DataFrame(rows)
        
        # 定义列顺序
        annual_columns = [
            '序号', '单位名称', '单位地址', '省', '市', '区', 
            '样品编号', '姓名', '性别', '职业类别'
        ] + quarters + ['年有效剂量当量', '是否超调查水平（5mSv）']
        
        # 确保所有列都存在
        for col in annual_columns:
            if col not in df.columns:
                df[col] = ''
        
        # 重新排序列
        df = df[annual_columns]
        
        # 生成文件路径
        filename = "年度汇总表.csv"
        output_path = os.path.join(output_dir, filename)
        
        # 确保输出目录存在
        os.makedirs(output_dir, exist_ok=True)
        
        # 保存CSV
        df.to_csv(output_path, index=False, encoding='utf-8-sig')
        print(f"年度汇总表已保存到: {output_path}")
        print(f"共处理了 {len(rows)} 个样品")
        
        # 显示统计信息
        over_limit = len([r for r in rows if r.get('是否超调查水平（5mSv）', r.get('是否超调查水平', '')) == '是'])
        print(f"超调查水平的样品: {over_limit} 个")
        
        return output_path
        
    def generate_all_summaries(self, quarters, output_dir, use_historical_data=False):
        """生成所有需要的汇总表
        
        Args:
            quarters: 季度列表
            output_dir: 输出目录
            use_historical_data: 是否使用历史数据模式
            
        Returns:
            dict: 包含生成的文件路径的字典
        """
        result_files = {}
        
        if use_historical_data:
            # 历史数据模式
            if len(quarters) == 1:
                # 单季度：直接复制历史季度汇总表
                self.update_progress(90, f"复制历史{quarters[0]}季度汇总表...")
                quarter = quarters[0]
                archives_dir = os.path.join(os.getcwd(), APP_SETTINGS['QUARTERLY_ARCHIVES_DIR'])
                source_file = os.path.join(archives_dir, f"{quarter}季度汇总表.csv")
                target_file = os.path.join(output_dir, f"{quarter}季度汇总表.csv")
                
                try:
                    os.makedirs(output_dir, exist_ok=True)
                    import shutil
                    shutil.copy2(source_file, target_file)
                    result_files['quarterly'] = {quarter: target_file}
                    print(f"历史季度汇总表已复制到: {target_file}")
                except Exception as e:
                    result_files['error'] = f"复制历史季度数据失败: {str(e)}"
            else:
                # 多季度：复制季度汇总表 + 生成年度汇总表
                self.update_progress(80, "复制历史季度汇总表...")
                
                # 先复制所有季度汇总表到结果目录
                archives_dir = os.path.join(os.getcwd(), APP_SETTINGS['QUARTERLY_ARCHIVES_DIR'])
                result_files['quarterly'] = {}
                
                try:
                    os.makedirs(output_dir, exist_ok=True)
                    import shutil
                    
                    for i, quarter in enumerate(quarters):
                        progress = 80 + (i / len(quarters)) * 10
                        self.update_progress(progress, f"复制{quarter}季度汇总表...")
                        
                        source_file = os.path.join(archives_dir, f"{quarter}季度汇总表.csv")
                        target_file = os.path.join(output_dir, f"{quarter}季度汇总表.csv")
                        
                        shutil.copy2(source_file, target_file)
                        result_files['quarterly'][quarter] = target_file
                        print(f"季度汇总表已复制: {quarter}季度汇总表.csv")
                    
                    # 然后生成年度汇总表
                    self.update_progress(90, "从历史数据生成年度汇总表...")
                    annual_file = self.generate_annual_from_historical(quarters, output_dir)
                    if annual_file:
                        result_files['annual'] = annual_file
                    else:
                        # 如果历史数据不完整，返回错误信息
                        result_files['error'] = f"缺少必要的历史季度数据，无法生成年度汇总表"
                        
                except Exception as e:
                    result_files['error'] = f"复制历史季度数据失败: {str(e)}"
        else:
            # 正常模式：从docx生成季度汇总表
            self.update_progress(85, "生成汇总表...")
            
            # 如果是单季度，只生成一个季度汇总表
            if len(quarters) == 1:
                quarter = quarters[0]
                self.update_progress(90, f"生成{quarter}季度汇总表...")
                quarterly_file = self.generate_quarterly_summary_csv(quarter, output_dir)
                if quarterly_file:
                    result_files['quarterly'] = {quarter: quarterly_file}
                
            # 如果是多季度，生成每个季度的汇总表 + 年度汇总表
            else:
                result_files['quarterly'] = {}
                
                # 生成每个季度的汇总表
                total_files = len(quarters) + 1  # 季度表 + 年度表
                for i, quarter in enumerate(quarters):
                    progress = 85 + (i / total_files) * 15
                    self.update_progress(progress, f"生成{quarter}季度汇总表...")
                    quarterly_file = self.generate_quarterly_summary_csv(quarter, output_dir)
                    if quarterly_file:
                        result_files['quarterly'][quarter] = quarterly_file
                
                # 生成年度汇总表
                self.update_progress(95, "生成年度汇总表...")
                annual_file = self.generate_annual_summary_csv(quarters, output_dir)
                if annual_file:
                    result_files['annual'] = annual_file
        
        self.update_progress(100, "完成")
        
        # 生成Excel文件
        self.update_progress(100, "生成Excel文件...")
        excel_files = self.convert_all_results_to_excel(output_dir)
        if excel_files:
            result_files['excel_files'] = excel_files
        
        return result_files
        
    def generate_output_directory(self, time_range, base_dir=None):
        """生成输出目录路径
        
        Args:
            time_range: 时间范围字符串
            base_dir: 基础目录，默认为results
            
        Returns:
            str: 输出目录路径
        """
        if base_dir is None:
            base_dir = APP_SETTINGS['RESULTS_DIR']
            
        time_range_formatted = format_time_range(time_range)
        timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
        dir_name = f"{time_range_formatted}_{timestamp}"
        
        # 创建结果目录
        results_dir = os.path.join(os.getcwd(), base_dir)
        ensure_directory(results_dir)
        
        output_dir = os.path.join(results_dir, dir_name)
        ensure_directory(output_dir)
        
        return output_dir
        
    def get_processing_summary(self, quarters):
        """获取处理摘要信息
        
        Args:
            quarters: 季度列表
            
        Returns:
            dict: 摘要信息
        """
        # 收集所有样品编号
        all_sample_ids = set()
        for quarter in quarters:
            if quarter in self.quarterly_data:
                all_sample_ids.update(self.quarterly_data[quarter].keys())
        
        summary = {
            'quarters': quarters,
            'total_samples': len(all_sample_ids),
            'over_limit_count': 0,
            'sample_details': []
        }
        
        # 根据季度数量选择不同的阈值（都使用大于等于）
        if len(quarters) == 1:
            # 单季度使用季度阈值
            threshold = APP_SETTINGS['QUARTERLY_DOSE_THRESHOLD']
        else:
            # 多季度使用年度阈值
            threshold = APP_SETTINGS['ANNUAL_DOSE_THRESHOLD']
        
        for sample_id in sorted(all_sample_ids):
            # 计算总剂量
            total = 0
            quarter_info_list = []
            for quarter in quarters:
                dose = 0
                if quarter in self.quarterly_data and sample_id in self.quarterly_data[quarter]:
                    dose = self.quarterly_data[quarter][sample_id].get('剂量当量', 0)
                quarter_info_list.append(f"{quarter}:{dose}")
                total += dose
            
            quarter_info = ', '.join(quarter_info_list)
            status = "超标" if total >= threshold else "正常"
            
            if total >= threshold:
                summary['over_limit_count'] += 1
            
            summary['sample_details'].append({
                'sample_id': sample_id,
                'quarter_info': quarter_info,
                'total_dose': total,
                'status': status
            })
        
        return summary
    
    def convert_csv_to_excel(self, csv_file_path, title="数据汇总"):
        """将CSV文件转换为Excel格式，并添加标题行
        
        Args:
            csv_file_path: CSV文件路径
            title: 标题文本
            
        Returns:
            str: 生成的Excel文件路径
        """
        try:
            # 读取CSV文件
            df = pd.read_csv(csv_file_path, encoding='utf-8-sig')
            
            # 生成Excel文件路径
            excel_file_path = csv_file_path.replace('.csv', '.xlsx')
            
            # 创建Excel文件
            with pd.ExcelWriter(excel_file_path, engine='openpyxl') as writer:
                # 将数据写入Excel，从第2行开始（为标题行留空间）
                df.to_excel(writer, sheet_name='Sheet1', index=False, startrow=1)
                
                # 获取workbook和worksheet
                workbook = writer.book
                worksheet = writer.sheets['Sheet1']
                
                # 合并第一行的所有列作为标题
                last_col = openpyxl.utils.get_column_letter(len(df.columns))
                worksheet.merge_cells(f'A1:{last_col}1')
                
                # 设置标题
                title_cell = worksheet['A1']
                title_cell.value = title
                
                # 设置标题样式（蓝色背景，白色字体，居中，加粗）
                title_cell.fill = PatternFill(start_color='5B9BD5', end_color='5B9BD5', fill_type='solid')
                title_cell.font = Font(color='FFFFFF', bold=True, size=14)
                title_cell.alignment = Alignment(horizontal='center', vertical='center')
                
                # 设置行高
                worksheet.row_dimensions[1].height = 25
                
                # 调整列宽（自动适应内容）
                for col_num in range(1, len(df.columns) + 1):
                    column_letter = openpyxl.utils.get_column_letter(col_num)
                    max_length = 0
                    
                    # 检查该列的所有单元格
                    for row_num in range(2, len(df) + 3):  # 从第2行开始（跳过标题行）
                        try:
                            cell = worksheet.cell(row=row_num, column=col_num)
                            if cell.value and len(str(cell.value)) > max_length:
                                max_length = len(str(cell.value))
                        except:
                            pass
                    
                    # 也检查表头的长度
                    try:
                        header_cell = worksheet.cell(row=2, column=col_num)
                        if header_cell.value and len(str(header_cell.value)) > max_length:
                            max_length = len(str(header_cell.value))
                    except:
                        pass
                    
                    adjusted_width = min(max(max_length + 2, 8), 30)  # 最小宽度8，最大宽度30
                    worksheet.column_dimensions[column_letter].width = adjusted_width
                
                # 设置表头样式（第2行）
                header_fill = PatternFill(start_color='D9E2F3', end_color='D9E2F3', fill_type='solid')
                header_font = Font(bold=True)
                
                for col_num in range(1, len(df.columns) + 1):
                    cell = worksheet.cell(row=2, column=col_num)
                    cell.fill = header_fill
                    cell.font = header_font
                    cell.alignment = Alignment(horizontal='center', vertical='center')
            
            print(f"Excel文件已生成: {excel_file_path}")
            return excel_file_path
            
        except Exception as e:
            print(f"转换Excel文件失败: {e}")
            return None
    
    def convert_all_results_to_excel(self, output_dir):
        """将结果目录中的所有CSV文件转换为Excel格式
        
        Args:
            output_dir: 结果目录路径
            
        Returns:
            list: 生成的Excel文件路径列表
        """
        excel_files = []
        
        try:
            # 查找所有CSV文件
            csv_files = glob.glob(os.path.join(output_dir, "*.csv"))
            
            for csv_file in csv_files:
                filename = os.path.basename(csv_file)
                
                # 根据文件名确定标题
                if "年度汇总表" in filename:
                    title = "数据汇总"
                elif "季度汇总表" in filename:
                    # 提取季度信息
                    if "Q1" in filename:
                        title = "数据汇总"
                    elif "Q2" in filename:
                        title = "数据汇总"
                    else:
                        title = "数据汇总"
                else:
                    title = "数据汇总"
                
                excel_file = self.convert_csv_to_excel(csv_file, title)
                if excel_file:
                    excel_files.append(excel_file)
            
            if excel_files:
                print(f"\\n共转换了 {len(excel_files)} 个Excel文件")
            
        except Exception as e:
            print(f"批量转换Excel文件失败: {e}")
        
        return excel_files
    
    def print_processing_summary(self, quarters):
        """打印处理摘要
        
        Args:
            quarters: 季度列表
        """
        summary = self.get_processing_summary(quarters)
        
        print(f"\n=== 处理摘要 ===")
        print(f"处理季度: {', '.join(quarters)}")
        print(f"样品编号总数: {summary['total_samples']}")
        print(f"超调查水平样品: {summary['over_limit_count']} 个")
        
        # 打印每个样品的详细信息
        for detail in summary['sample_details']:
            print(f"  {detail['sample_id']}: {detail['quarter_info']} -> 总计:{detail['total_dose']} ({detail['status']})")
